package ink.yuanchu.picachoframework.controller;

import ink.yuanchu.picachoframework.config.FileConfig;
import ink.yuanchu.picachoframework.exception.BusinessException;
import ink.yuanchu.picachoframework.message.Message;
import ink.yuanchu.picachoframework.message.ResultBody;
import ink.yuanchu.picachoframework.service.FileService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @author ziyuan
 * @Date: 2021/04/02/9:50
 * @Description:
 */
@RestController
@RequestMapping("/picachoframework/fileController")
@Api("文件控制层")
public class FileController {

    @Autowired
    private FileConfig fileConfig;

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResultBody fileUpload(@RequestParam("file") MultipartFile file){

        ink.yuanchu.picachoframework.entity.File fileInfo = new ink.yuanchu.picachoframework.entity.File();

        String filePath = fileConfig.getUploadPath();
        File fileTemp = new File(filePath);

        if (!fileTemp.isDirectory()) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.toString(), Message.FILE_PATH_DOES_NOT_EXIST);
        }

        if (file.isEmpty()) {
            return ResultBody.error(Message.FILE_DOES_NOT_EXIST);
        }

        long size = file.getSize();
        String fileName = file.getOriginalFilename();
        String format = getFileFormat(fileName);
        String newFileName = UUID.randomUUID().toString() + format;
        String fileAddress = filePath + newFileName;

        File dest = new File(fileAddress);

        fileInfo.setExternalName(fileName);
        fileInfo.setTrueName(newFileName);
        fileInfo.setFormat(format);
        fileInfo.setSize(String.valueOf(size));
        try {
            //写入文件
            file.transferTo(dest);
            //保存文件信息到数据库
            Boolean isTrue = fileService.saveFileInfo(fileInfo);
            if (isTrue) {
                return ResultBody.success(Message.UPLOAD_SUCCESS);
            } else {
                //保存失败，删除文件
                deleteFile(fileAddress);
                //抛异常 全局异常处理会将异常返回给前台
                throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.toString(), Message.FILE_PATH_DOES_NOT_EXIST);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBody.success(Message.UPLOAD_ERROR);
        }
    }

    @PostMapping("/deleteFileTest")
    public Boolean deleteFileTest(@RequestBody String req){
        Boolean aBoolean = deleteFile(req);
        return aBoolean;
    }

    /**
     * 删除文件
     * @param fileInfo
     * @return
     */
    private Boolean deleteFile(String fileInfo){
        File file = new File(fileInfo);
        // 如果是一个文件夹直接退出，避免删除了这个文件夹的所有东西
        if (file.isDirectory()){
            return false;
        }
        if (file.exists() && file.isFile()) {
            boolean delete = file.delete();
            return delete;
        }
        return false;
    }

    /**
     * 获取文件格式
     * @param fileName  文件名
     * @return 文件格式
     */
    private String getFileFormat(String fileName){
        String format = "";
        for (int i = fileName.length(); i > 0 ; i--) {
            String temp = String.valueOf(fileName.charAt(i-1));
            if (temp.equals(".")){
                format = format+".";
                String trans = format;
                format = "";
                for (int j = trans.length(); j > 0; j--) {
                    format = format + String.valueOf(trans.charAt(j-1));
                }
                return format;
            }else {
                format = format + temp;
            }
        }
        return null;
    }
}
